//
//  RZNewFeatureViewController.m
//  
//
//  Created by reyzhang on 2018/5/29.
//  Copyright © 2018年. All rights reserved.
//

#import "RZNewFeatureViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>


@interface RZNewFeatureViewController ()
@property (nonatomic, strong) AVPlayer *avPlayer;
@property (nonatomic, strong) AVAudioSession *avaudioSession;


@end

@implementation RZNewFeatureViewController {
    AVPlayerItem *_playItem;
}

- (instancetype)initWithMovieFile:(NSString *)movie {
    if (self = [super init]) {
        self.movie_url = movie;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.movie_url = @"1.mp4";
    /**
     *  设置其他音乐软件播放的音乐不被打断
     */
    self.avaudioSession = [AVAudioSession sharedInstance];
    NSError *error = nil;
    [self.avaudioSession setCategory:AVAudioSessionCategoryAmbient error:&error];

    [self initUI];
}


- (void)initUI {
    [self creatPlayUI];
}

- (void)creatPlayUI {
    
    // 创建播放界面层
    AVPlayerLayer *player = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
    
    // 设置layer的frame
    player.frame = [UIScreen mainScreen].bounds;
    
    //
    [self.view.layer addSublayer:player];
    
    [self.moviePlayer play];
}

- (void)setMovie_url:(NSString *)movie_url {
    _movie_url = movie_url;
    if (_movie_url.length > 0) {
        _playItem = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:_movie_url ofType:nil]]];
        if (_playItem && self.avPlayer) {
            [self.avPlayer replaceCurrentItemWithPlayerItem:_playItem];
        }
    }
}


#pragma mark NSNotificationCenter Handler
- (void)statusChanged {
    
    if (AVPlayerItemStatusReadyToPlay) {
        [self.avPlayer play];
    }
}

// 视频播放完成的时候，再次进行播放
- (void)playStatusChanged:(NSNotification *)notification{
    //注册的通知  可以自动把 AVPlayerItem 对象传过来，只要接收一下就OK
    
    AVPlayerItem * playItem = [notification object];
    //关键代码
    [playItem seekToTime:kCMTimeZero];
    
    [_avPlayer play];
}


#pragma mark Dealloc
- (void)dealloc {
    
    if (AVPlayerItemDidPlayToEndTimeNotification) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    
    if (@"statusChanged") {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:nil];
    }
    
}


#pragma mark Lazy Load
- (AVPlayer *)avPlayer {
    if (!_avPlayer) {
        
        _avPlayer = [[AVPlayer alloc] initWithPlayerItem:_playItem];
        
        /*监听播放状态*/
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playStatusChanged:) name:AVPlayerItemDidPlayToEndTimeNotification  object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusChanged) name:nil object:nil];
    }

    return _avPlayer;
    
}

@end
